package org.soenea.doitall.domain.model.group.mapper;

import java.sql.SQLException;

import org.dsrg.soenea.domain.MapperException;
import org.dsrg.soenea.domain.mapper.LostUpdateException;
import org.soenea.doitall.domain.model.group.Group;
import org.soenea.doitall.domain.model.group.data.GroupTDG;
import org.soenea.doitall.domain.model.person.Person;
import org.soenea.doitall.domain.model.person.data.PersonTDG;

public class GroupOutputMapper {

	public static void delete(Group d) throws MapperException {
		try {
			final int count =  GroupTDG.delete(d.getId(), d.getVersion());
			throwLostUpdateOnCountOfZero(d, count);
		} catch (final SQLException e) {
			throw new MapperException(e);
		}
	}

	public static void insert(Group d) throws MapperException {
		try {
			GroupTDG.insert(d.getId(), d.getVersion(), d.getName(),d.getDescription());
		} catch (final SQLException e) {
			throw new MapperException(e);
		}
	}

	private static void throwLostUpdateOnCountOfZero(Group p, int count)
			throws LostUpdateException {
		if (count == 0)
			throw new LostUpdateException("Group: id = " + p.getId()
					+ "; version = " + p.getVersion() + " not found");
	}

	public static void update(Group d) throws MapperException {
		try {
			final int count = GroupTDG.update(d.getId(), d.getVersion(), d.getName(), d.getDescription());
			throwLostUpdateOnCountOfZero(d, count);
			d.setVersion(d.getVersion() + 1);
		} catch (final SQLException e) {
			throw new MapperException(e);
		}
	}
}
